<template>
  <el-dialog :title="isEdit ? '设置角色权限': '角色权限信息'" :visible.sync="visible" :close-on-click-modal="closeOnClickModal" @open="_handleDialogOpen" @close="_cancel">
    <el-form ref="dataForm" :model="form" :status-icon="true" :rules="formRules" label-position="top" label-width="100px">
      <el-form-item>
        <div class="detail-tree">
          <div class="buttons">
            <el-button type="primary" size="mini" plain @click="functionCheckSet()">全选/取消</el-button>
            <!-- <el-button type="default" size="mini" plain @click="functionExpandAll = !functionExpandAll">展开/关闭</el-button> -->
          </div>
          <el-tree
            ref="elTreeRef"
            :is-loading="functionLoading"
            :data="functionTree"
            :props="functionProps"
            :default-expand-all="functionExpandAll"
            :default-checked-keys="form.functionIdList"
            node-key="id"
            empty-text="暂无数据"
            highlight-current
            show-checkbox
            @check-change="functionCheckChange" />
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="_cancel">取 消</el-button>
      <el-button :loading="_loading" size="small" type="primary" @click="_ok">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

// import waves from '@/directive/waves' // Waves directive
import { mapGetters } from 'vuex'
// import dicData from './dic-data'
import { getUserFunctionTree } from '@/api/systemManage/function'
import { getRoleMenu } from '@/api/systemManage/role'

export default {

  props: {
    closeOnClickModal: {
      type: Boolean,
      default: false
    },

    loading: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      isEdit: false,
      visible: false,
      form: {},
      formRules: {},

      functionLoading: false,
      functionTree: [],
      functionProps: {
        label: 'sysName'
      },
      functionIsCheckAll: false,
      functionExpandAll: false
    }
  },

  computed: {

    ...mapGetters([
      'lang',
      'userId'
    ]),

    '_loading': {
      get() {
        return this.loading
      },

      set(value) {
        this.$emit('update:loading', value)
      }
    }
  },

  methods: {
    _handleDialogOpen() {
      this.getFunction()
      this.formReset()
      this.$emit('open')
    },

    _cancel() {
      this.formReset()
      this.visible = false
      this.isLoading = false
      this.$emit('cancel')
    },

    _ok() {
      const form = this.$refs['dataForm']
      form.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          this.$emit('ok', formData, this.isEdit)
        }
      })
    },

    show(params) {
      this.visible = true
      if (params) {
        this.isEdit = true
        getRoleMenu(params).then(resp => {
          this.form.functionIdList = resp.data || []
          this.form.id = params.roleid
          // if (this.form.type && typeof this.form.type === 'string') {
          //   this.form.type = this.form.type.split(',')
          // }
        }).catch(resp => {
          this.$message.error(resp.message)
        })
      } else {
        // pass
        this.isEdit = false
        // this._clear()
      }
    },

    close() {
      this._cancel()
    },

    formReset() {
      this.form = {
        id: '',
        functionIdList: []
      }
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields()
      })
    },

    getFunction() {
      this.functionLoading = true
      getUserFunctionTree({ userId: this.userId }).then(res => {
        this.functionLoading = false
        if (res.code === 200) {
          this.functionTree = res.data
        } else this.$message.error(res.message)
      }).catch(e => {
        this.functionLoading = false
        this.$message.error(e.message)
      })
    },

    functionCheckSet(type) {
      this.functionIsCheckAll = type !== undefined ? type : !this.functionIsCheckAll
      if (this.functionIsCheckAll) {
        const keys = this.getFunctionAllKey(this.functionTree)
        this.$refs.elTreeRef.setCheckedKeys(keys)
      } else {
        this.$refs.elTreeRef.setCheckedKeys([])
      }
    },

    getFunctionAllKey(nodes) {
      const arr = []
      for (let i = 0; i < nodes.length; i++) {
        arr.push(nodes[i].id)
        if (Array.isArray(nodes[i].children) && nodes[i].children.length) {
          arr.push(...this.getFunctionAllKey(nodes[i].children))
        }
      }
      return arr
    },

    functionCheckChange() {
      const keys = this.$refs.elTreeRef.getCheckedKeys()
      this.form.functionIdList = keys
      this.$forceUpdate()
    }
  }
}
</script>
